import json

from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render
# coding=utf-8
# Create your views here.
from django.views import View

from apps.areas.models import Area
from celery_tasks.email.tasks import logger


# 查询省数据后端逻辑实现
class AreasView(View):
    """省市区数据"""
    def get(self, request):

        # 使用缓存、先查询有无缓存数据
        province_list = cache.get('province')
        if province_list is None:
            # parent__isnull=True 根据parent_id 是null查询出所有的省份
            province_model_list = Area.objects.filter(parent__isnull=True)

            # 序列化省级数据
            province_list = []
            for province_model in province_model_list:
                province_list.append({'id': province_model.id,
                                      'name': province_model.name})
            cache.set('province', province_list, 24*3600)
        # 响应市或区数据
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'province_list': province_list})


# 查询市区数据后端逻辑实现
class SubAreasView(View):
    """省市区数据"""
    def get(self, request, id):
        data_list = cache.get('city:%s' % id)

        if data_list is None:
            parent_model = Area.objects.get(id=id)
            sub_model_list = parent_model.subs.all()

            # 序列化市或区数据
            data_list = []
            for sub_model in sub_model_list:
                data_list.append({
                    'id': sub_model.id,
                    'name': sub_model.name})
            cache.set('city:%s' % id, data_list, 24*3600)
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': {'subs': data_list}})
